package cn.itcast.search.filter;

import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldwine
 * @date 2022/6/22
 * @Version 1.0
 */
public class UserIdInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头信息
        String header = request.getHeader("authorization");
        if (!StringUtils.isEmpty(header)) {
            //2.将用户id数据放入线程中
            ThreadLocalUtil.setUserId(Long.valueOf(header));
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
